﻿package net.wangit.dev.component;

import net.wangit.MapList;
import net.wangit.Row;
import net.wangit.context.ActionContext;
import net.wangit.dev.LabelRule;
import net.wangit.dev.ReferenceUtil;
import net.wangit.jdbc.DB;
import net.wangit.util.Checker;
import net.wangit.view.tree.Tree;

public class TableTree extends ObjectTree {

	private static final String PREFIX = "_01C";
	private static final String TYPE = Integer.toString(1);
	private static final String TABLE_SQL = "select t,tl,l,gid from TABLE order by o,t";
	private static final String COUNT_NAME = "rowcount";
	private static final String ITEM_SQL = "select count(*) rowcount from COLUMN where t=?";

	public TableTree() {
	}

	protected String getItemsTableName() {
		return "COLUMN";
	}

	protected String getComponentType() {
		return TYPE;
	}

	protected MapList getObjects(DB db) throws Exception {
		MapList objects = db.query(TableTree.TABLE_SQL);
		objectCount = Checker.isEmpty(objects) ? 0 : objects.size();
		return objects;
	}

	protected boolean showNullGroup() {
		return true;
	}

	protected String getGroupAttribute() {
		return "oncontextmenu=wmg1()";
	}

	protected int addObject(ActionContext ac, DB db, Tree parent, Row row)
			throws Exception {
		int itemCount = 0;
		Tree object = new Tree();
		String tableName = row.get("t");
		object.setId((new StringBuilder(TableTree.PREFIX)).append(tableName)
				.toString());
		String name = row.get("tl");
		String status = row.get("l", "0");
		object.setIcon((new StringBuilder("/domain/dev/c/table"))
				.append(status).append(".png").toString());
		if (check) {
			name = (new StringBuilder(String.valueOf(tableName))).append(" ")
					.append(name).toString();
		} else {
			int referenceCount = ReferenceUtil.getTableReferenceCount(db,
					tableName);
			itemCount = getItemCount(db, tableName);
			String label = LabelRule.getLabel(ac, ObjectTreeHelper
					.getLableRule(ac), tableName, name);
			name = (new StringBuilder(String.valueOf(referenceCount))).append(
					" ").append(label).append(" ").append(itemCount).toString();
			object.setAttribute("oncontextmenu=wm1()");
			object
					.setAction((new StringBuilder(
							"/dev/table.do?m=e&tablename=")).append(tableName)
							.toString());
		}
		object.setName(name);
		parent.add(object);
		return itemCount;
	}

	private int getItemCount(DB db, String unitId) throws Exception {
		MapList list = db.query(TableTree.ITEM_SQL, unitId, 2);
		return list.getRow(0).getInt(TableTree.COUNT_NAME, 0);
	}

}
